package com.yxsk.relay.job.admin.core.trigger.quartz.interceptor;

import com.yxsk.relay.job.admin.core.schedule.quartz.context.TriggerContext;
import com.yxsk.relay.job.admin.core.schedule.quartz.vo.JobConfig;
import com.yxsk.relay.job.admin.core.trigger.interceptor.TaskExecuteInterceptor;
import com.yxsk.relay.job.admin.data.entity.JobExecuteLog;
import com.yxsk.relay.job.admin.data.service.JobExecuteLogService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Author 11376
 * @CreaTime 2019/6/22 17:21
 * @Description
 */
@Slf4j
@AllArgsConstructor
public class QuartzExecuteBlockInterceptor implements TaskExecuteInterceptor {

    private JobExecuteLogService logService;

    @Override
    public boolean intercept(TriggerContext context) {
        JobConfig jobConfig = context.getJobConfig();
        if (JobConfig.BlockStrategy.SERIAL.equals(jobConfig.getBlockStrategy())) {
            List<JobExecuteLog> logs = this.logService.findExecutingLog(jobConfig.getId());
            if (!CollectionUtils.isEmpty(logs)) {
                for (JobExecuteLog executeLog : logs) {
                    if (!executeLog.getTriggerLogId().equals(context.getTriggerInfo().getTriggerId())) {
                        // 已有任务在执行
                        return false;
                    }
                }
            }
        }
        return true;
    }

}
